<template>
  <card ref="Card" class="mb-15">
    <div slot="header">
      <span>分配单号</span>
      <submit-button ref="Submit" type="success" @submit="submit" class="float-right" text="分配"/>
    </div>
    <el-form :model="form" :rules="rules" ref="Form" inline label-width="100px" hide-required-asterisk>
      <row-col>
        <el-form-item prop="begin">
          <el-input v-model.trim="form.begin" placeholder="开始号码" clearable></el-input>
        </el-form-item>
        <el-form-item prop="end">
          <el-input v-model.trim="form.end" placeholder="结束号码" clearable></el-input>
        </el-form-item>
        <el-form-item label="分配网点:" prop="userId" slot="r">
          <search-select-lower v-model="form.userId"/>
        </el-form-item>
      </row-col>
    </el-form>
  </card>
</template>

<script>
  import SearchSelectLower from "@/views/components/SearchSelectLower";
  import {validateThirteenNumber} from "@/utils/validate";
  import {resetForm} from "@/utils/common";
  import {allotApi} from "@/api/order/number";

  export default {
    name: "Allot",
    components: {SearchSelectLower},
    data() {
      return {
        max: 30000,
        form: {
          begin: '',
          end: '',
          userId: null
        },
        rules: {
          begin: [
            {required: true, message: '请输入开始号码', trigger: 'blur'},
            {validator: validateThirteenNumber, trigger: 'blur'}
          ],
          end: [
            {required: true, message: '请输入结束号码', trigger: 'blur'},
            {validator: validateThirteenNumber, trigger: 'blur'}
          ],
          userId: {required: true, message: '请选择网点', trigger: 'change'}
        }
      }
    },
    methods: {
      submit() {
        this.$refs['Form'].validate(valid => {
          if (!valid) return false;
          let data = {...this.form};
          data.begin = data.begin / 1;
          data.end = data.end / 1;
          if (data.begin > data.end) {
            this.$errorMsg('结束号码不得小于开始号码');
            return;
          }
          if (data.end - data.begin > this.max) {
            this.$errorMsg(`一次分配不得超过 ${this.max} 条`);
            return;
          }
          this.$msgBox('确认分配？').then(() => {
            this.$refs.Submit.start();
            allotApi(data).then(result => {
              this.$refs.Submit.stop();
              if (result.status === 200) this.cancel()
            }).catch(() => {
              this.$refs.Submit.stop();
            })
          })
        });
      },
      cancel() {
        resetForm(this)
      }
    }
  }
</script>
